import {
    StyleSheet,
    Text,
    View,
    ImageBackground,
    ScrollView,
    TouchableOpacity,
    Pressable,
    Image,
    Animated,
    TextInput,
} from 'react-native';
import React, { useEffect, useState, useRef } from 'react';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Modal from 'react-native-modal';
import { useTranslation } from 'react-i18next';
import { useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import FastImage from '@d11/react-native-fast-image';
import {
    applyBloodDevice,
    pointerMethod1,
    applyThemeArray,
    screenLightArray,
    uploadArray,
    wifiDevices,
    offlineCourseDevices,
} from '~/utils/deviceMenues';
import { FocusAwareStatusBar, DialogModal, MyLoading } from '~/components';
import { deviceStore, observer, userStore } from '~/store';
import { isIos, px2dp, scale, width } from '~/utils/px2dp';
import { getDeviceDetails, updateDeviceAlias, unbindDeviceApi } from '~/api/deviceApi';
import {
    setScreenLight,
    getScreenLight,
    recoverBleDevice,
    setBleHeartAutoState,
    setWifiStatus,
} from '~/utils/ble/application';
import { getDeviceDataHead } from '~/utils/ble/getBleData';
import { useRequestWithTimeout } from '~/common';

export default observer(() => {
    const { t } = useTranslation();
    const insets = useSafeAreaInsets();
    const navigation: any = useNavigation();
    const goBack = () => {
        navigation.goBack();
    };
    const animatedValue = useRef(new Animated.Value(0)).current;
    const { connectDeviceInfo } = deviceStore;
    // 设备信息
    const heightInterpolate = animatedValue.interpolate({
        inputRange: [0, 1],
        outputRange: ['0%', '100%'],
    });
    const [deviceInfo, setDeviceInfo] = useState<any>({});
    const getData = () => {
        const device_sn = deviceStore.device.connectDevice?.device_sn;
        getDeviceDetails({ device_sn }).then((res) => {
            if (res.status == 1) {
                const data = res.data;
                data.num = data.device_sn.substring(device_sn.length - 3);
                setDeviceInfo(data);
            } else {
                if (res.msg == '设备不存在,请联系客服!') {
                    Toast.show({ content: t('DeviceDetailes.t1'), layout: 'top' });
                } else {
                    Toast.show({ content: res.msg });
                }
                setDeviceInfo({});
            }
        });
    };
    // 设置设备别名
    const [deviceAlias, setDeviceAlias] = useState('');
    const [visible, setVisible] = useState(false);
    const saveDeviceAlias = () => {
        const device_sn = deviceStore.device.connectDevice?.device_sn;
        updateDeviceAlias({
            device_sn,
            device_alias: deviceAlias,
        }).then((res) => {
            if (res.status == 1) {
                getData();
                setVisible(false);
            } else {
                Toast.show({ content: res.msg });
            }
        });
    };
    // 解绑设备
    const [unbindVisible, setUnbindVisible] = useState(false);
    const unbindDevice = () => {
        const device_sn = deviceStore.device.connectDevice?.device_sn;
        unbindDeviceApi({ device_sn }).then((res) => {
            setUnbindVisible(false);
            if (res.status == 1) {
                if (deviceStore.device.connectedDeviceStatus == 1 && device_sn == deviceInfo?.device_sn) {
                    deviceStore.disConnectble();
                }
                if (userStore.autoConnectDeviceSn == device_sn) {
                    userStore.signAutoConnectDevice(''); // 清空对应的自动连接设备
                }
                navigation.goBack();
            } else {
                Toast.show({ content: res.msg });
            }
        });
    };
    // 设置抬手亮屏
    const getLightStatus = () => {
        getScreenLight(1, { type: 'ble' });
    };
    const setLightStatus = () => {
        const { screenStatus } = deviceStore;
        setScreenLight(screenStatus ? 0 : 1, { type: 'ble' });
        setTimeout(() => {
            getLightStatus();
        }, 500);
    };
    // 设备功能
    const goDeviceTool = (router) => {
        const navigationParams = {
            type: 'ble',
            // device_sn: deviceInfo.device_sn,
            subDevice_sn: deviceInfo.device_sn,
            device_code: deviceInfo.device_code,
        };
        deviceStore.singRemoteInfo(navigationParams);
        navigation.navigate(router, navigationParams);
    };

    // 恢复出厂设备
    const [recoverVisible, setRecoverVisible] = useState(false);
    const recover = () => {
        recoverBleDevice();
        setTimeout(() => {
            deviceStore.disConnectble();
            navigation.goBack();
        }, 200);
    };
    // 空中升级
    const UpdateDfuDevice = () => {
        if (deviceStore.connectDeviceInfo.protocolStackVersion.includes('S')) {
            navigation.navigate('UpdateDfuDevice');
        } else {
            navigation.navigate('ChinaUpgrade');
        }
    };
    // 上传数据
    const { loadingRef, run } = useRequestWithTimeout(10000);
    const uploadData = () => {
        run(
            () =>
                new Promise((resolve, reject) => {
                    getDeviceDataHead((res: any) => {
                        resolve(res);
                    });
                }),
            (res) => {
                Toast.show({ content: t('DeviceDetailes.t27') });
            },
        );
    };
    // 设置自动心率
    const setHeartRateStatus = () => {
        setBleHeartAutoState({ type: 'ble' }, deviceStore.zHeartRateDataStatus == 1 ? 0 : 1);
    };
    // 配网
    const goWifi = (type = 'normal') => {
        setWifiStatus(1);
        navigation.navigate('DeviceWifi', { actionType: type });
    };
    // 开启自动连接/清除
    const autoConnectDevice = () => {
        if (userStore.autoConnectDeviceSn == deviceStore.device.connectDevice.device_sn) {
            userStore.signAutoConnectDevice('');
            return;
        }
        userStore.signAutoConnectDevice(deviceInfo?.device_sn);
    };

    useEffect(() => {
        if (screenLightArray.indexOf(deviceStore.device?.connectDevice?.device_code) !== -1) {
            getLightStatus();
        }
        getData();
    }, []);

    useEffect(() => {
        Animated.timing(animatedValue, {
            toValue: connectDeviceInfo.eq / 100,
            duration: 300, // 动画持续时间
            useNativeDriver: false,
        }).start();
    }, [connectDeviceInfo.eq]);

    return (
        <View style={styles.container}>
            <FocusAwareStatusBar translucent={true} barStyle={'light-content'} />
            <ImageBackground
                style={[styles.bg, { paddingTop: isIos() ? insets.top : insets.top + px2dp(32) }]}
                source={require('~/assets/login/bg4.png')}>
                <View style={[styles.row, styles.between]}>
                    <Pressable onPress={goBack} style={{ width: px2dp(80) }}>
                        <Icon name={'chevron-back-outline'} size={px2dp(50)} color={'#fff'}></Icon>
                    </Pressable>
                    <Text style={styles.title}>{t('DeviceDetailes.t2')}</Text>
                    <View />
                </View>
                <ScrollView contentContainerStyle={styles.contenetStyle} showsVerticalScrollIndicator={false}>
                    <View style={[styles.nav, styles.row, styles.between]}>
                        <Pressable style={[styles.row]} onPress={() => setVisible(true)}>
                            <Text style={styles.tips}>{deviceInfo.device_alias || t('DeviceDetailes.t3')}</Text>
                            <Icon name={'create-outline'} size={px2dp(40)} color={'#fff'}></Icon>
                        </Pressable>
                        <Pressable onPress={uploadData}>
                            <Image source={require('~/assets/home/upload.png')} style={styles.upload} />
                        </Pressable>
                    </View>
                    <View style={[styles.row, styles.between]}>
                        <View style={[styles.row, { alignItems: 'flex-end' }]}>
                            <View>
                                <Text style={styles.eq}>{connectDeviceInfo.eq}%</Text>
                                <Text style={styles.device_code}>
                                    {t('DeviceDetailes.t4')}：{deviceInfo?.device_code}
                                </Text>
                                <Text style={styles.device_code}>
                                    {t('DeviceDetailes.t5')}：V{deviceInfo?.firmware_sn}
                                </Text>
                                <Text style={styles.device_code}>{deviceInfo?.device_sn}</Text>
                            </View>
                            <View style={styles.barContainer}>
                                <View style={styles.barBackground} />
                                <Animated.View style={[styles.bar, { height: heightInterpolate }]} />
                            </View>
                        </View>
                        <FastImage
                            style={styles.device_image}
                            source={{
                                uri: deviceInfo.device_image,
                                priority: FastImage.priority.normal,
                            }}
                            resizeMode={FastImage.resizeMode.contain}
                        />
                    </View>
                    {userStore.userBindDeviceData.length > 1 && (
                        <View style={[styles.card, styles.row, styles.between]}>
                            <Text style={styles.t1}>{t('DeviceDetailes.t32')}</Text>
                            <Pressable onPress={autoConnectDevice}>
                                <Image
                                    style={styles.switchIcon}
                                    resizeMode="contain"
                                    source={
                                        userStore.autoConnectDeviceSn == deviceStore.device.connectDevice.device_sn
                                            ? require('~/assets/device/open.png')
                                            : require('~/assets/device/close.png')
                                    }
                                />
                            </Pressable>
                        </View>
                    )}

                    <View style={styles.card}>
                        <Text style={styles.card_title}>{t('DeviceDetailes.t6')}</Text>
                        <View style={styles.menue}>
                            {applyBloodDevice.indexOf(deviceInfo?.device_code) !== -1 && (
                                <Pressable style={[styles.listItem]} onPress={() => goDeviceTool('OpenBlood')}>
                                    <Image style={styles.icons} source={require('~/assets/device/blood.png')} />
                                    <Text style={styles.t1}>{t('DeviceDetailes.t7')}</Text>
                                </Pressable>
                            )}
                            {applyBloodDevice.indexOf(deviceInfo?.device_code) == -1 && (
                                <Pressable style={[styles.listItem]} onPress={() => goDeviceTool('OpenHeart')}>
                                    <Image style={styles.icons} source={require('~/assets/device/heart.png')} />
                                    <Text style={styles.t1}>{t('DeviceDetailes.t8')}</Text>
                                </Pressable>
                            )}
                            <Pressable style={[styles.listItem]} onPress={() => goDeviceTool('OpenLaser')}>
                                <Image style={styles.icons} source={require('~/assets/device/laser.png')} />
                                <Text style={styles.t1}>{t('DeviceDetailes.t9')}</Text>
                            </Pressable>

                            <Pressable
                                style={[styles.listItem]}
                                onPress={() =>
                                    goDeviceTool(
                                        offlineCourseDevices.indexOf(deviceInfo?.device_code) == -1
                                            ? 'HealthManagement'
                                            : 'HealthOfflineManagement',
                                    )
                                }>
                                <Image style={styles.icons} source={require('~/assets/device/course.png')} />
                                <Text style={styles.t1} numberOfLines={1}>
                                    {t('DeviceDetailes.t10')}
                                </Text>
                            </Pressable>
                            <Pressable style={[styles.listItem]} onPress={() => goDeviceTool('BleToolMenues')}>
                                <Image style={styles.icons} source={require('~/assets/device/deviceTool.png')} />
                                <Text style={styles.t1}>{t('DeviceDetailes.t26')}</Text>
                            </Pressable>
                            <Pressable style={[styles.listItem]} onPress={UpdateDfuDevice}>
                                <Image style={styles.icons} source={require('~/assets/device/dfuManager.png')} />
                                <Text style={styles.t1}>{t('DeviceDetailes.t11')}</Text>
                            </Pressable>
                            {wifiDevices.indexOf(deviceInfo?.device_code) !== -1 && (
                                <Pressable style={[styles.listItem]} onPress={() => goWifi('normal')}>
                                    <Image style={styles.icons} source={require('~/assets/device/wifi.png')} />
                                    <Text style={styles.t1}>{t('DeviceDetailes.t30')}</Text>
                                </Pressable>
                            )}
                        </View>
                    </View>
                    <View style={styles.card}>
                        <Text style={styles.card_title}>{t('DeviceDetailes.t12')}</Text>
                        {applyThemeArray.indexOf(deviceInfo?.device_code) !== -1 && (
                            <Pressable
                                style={[styles.setList, styles.row, styles.between]}
                                onPress={() => goDeviceTool('WatchTheme')}>
                                <Text style={styles.t1}>{t('DeviceDetailes.t13')}</Text>
                                <Icon name="chevron-forward-outline" size={px2dp(40)} color={'#a4a4a4'}></Icon>
                            </Pressable>
                        )}
                        {deviceInfo?.device_code?.includes('HA05') ||
                            (deviceInfo?.device_code?.includes('HA06') && (
                                <Pressable
                                    style={[styles.setList, styles.row, styles.between]}
                                    onPress={() => {
                                        if (pointerMethod1.indexOf(deviceInfo?.device_code) !== -1) {
                                            goDeviceTool('BlePointer');
                                        } else {
                                            goDeviceTool('BlePointerBy05T');
                                        }
                                    }}>
                                    <Text style={styles.t1}>{t('DeviceDetailes.t25')}</Text>
                                    <Icon name="chevron-forward-outline" size={px2dp(40)} color={'#a4a4a4'}></Icon>
                                </Pressable>
                            ))}
                        {applyBloodDevice.indexOf(deviceInfo?.device_code) !== -1 && (
                            <>
                                <Pressable
                                    style={[styles.setList, styles.row, styles.between]}
                                    onPress={() => goDeviceTool('WatchCalibration')}>
                                    <Text style={styles.t1}>{t('DeviceDetailes.t14')}</Text>
                                    <Icon name="chevron-forward-outline" size={px2dp(40)} color={'#a4a4a4'}></Icon>
                                </Pressable>
                                <Pressable
                                    style={[styles.setList, styles.row, styles.between]}
                                    onPress={() => goDeviceTool('WatchTiming')}>
                                    <Text style={styles.t1}>{t('DeviceDetailes.t15')}</Text>
                                    <Icon name="chevron-forward-outline" size={px2dp(40)} color={'#a4a4a4'}></Icon>
                                </Pressable>
                                <Pressable
                                    style={[styles.setList, styles.row, styles.between]}
                                    onPress={() => goDeviceTool('WatchMonitor')}>
                                    <Text style={styles.t1}>{t('DeviceDetailes.t16')}</Text>
                                    <Icon name="chevron-forward-outline" size={px2dp(40)} color={'#a4a4a4'}></Icon>
                                </Pressable>
                            </>
                        )}
                        {applyBloodDevice.indexOf(deviceInfo?.device_code) == -1 && (
                            <Pressable
                                style={[styles.setList, styles.row, styles.between]}
                                onPress={() => goDeviceTool('WatchCalibration')}>
                                <Text style={styles.t1}>{t('DeviceDetailes.t29')}</Text>
                                <Pressable onPress={setHeartRateStatus}>
                                    <Image
                                        style={styles.switchIcon}
                                        resizeMode="contain"
                                        source={
                                            deviceStore.zHeartRateDataStatus == 1
                                                ? require('~/assets/device/open.png')
                                                : require('~/assets/device/close.png')
                                        }
                                    />
                                </Pressable>
                            </Pressable>
                        )}
                        {screenLightArray.indexOf(deviceInfo?.device_code) !== -1 && (
                            <Pressable style={[styles.setList, styles.row, styles.between]}>
                                <Text style={styles.t1}>{t('DeviceDetailes.t17')}</Text>
                                <Pressable onPress={setLightStatus}>
                                    <Image
                                        style={styles.switchIcon}
                                        resizeMode="contain"
                                        source={
                                            deviceStore.screenStatus == 1
                                                ? require('~/assets/device/open.png')
                                                : require('~/assets/device/close.png')
                                        }
                                    />
                                </Pressable>
                            </Pressable>
                        )}
                        {uploadArray.indexOf(deviceInfo?.device_code) !== -1 && (
                            <Pressable
                                style={[styles.setList, styles.row, styles.between]}
                                onPress={() => navigation.navigate('UploadSettings')}>
                                <Text style={styles.t1}>{t('DeviceDetailes.t31')}</Text>
                                <Icon name="chevron-forward-outline" size={px2dp(40)} color={'#a4a4a4'}></Icon>
                            </Pressable>
                        )}
                        <Pressable
                            style={[styles.setList, styles.row, styles.between, { borderBottomWidth: 0 }]}
                            onPress={() => setRecoverVisible(true)}>
                            <Text style={[styles.t1, { color: 'red' }]}>{t('DeviceDetailes.t18')}</Text>
                            <Icon name="chevron-forward-outline" size={px2dp(40)} color={'#a4a4a4'}></Icon>
                        </Pressable>
                    </View>
                </ScrollView>
                <View style={styles.bottom}>
                    <TouchableOpacity style={styles.bootom_button} onPress={() => setUnbindVisible(true)}>
                        <Text style={styles.bootom_buttonText}>{t('DeviceDetailes.t19')}</Text>
                    </TouchableOpacity>
                </View>
            </ImageBackground>
            <Modal
                isVisible={visible}
                presentationStyle="overFullScreen"
                onBackdropPress={() => setVisible(false)}
                statusBarTranslucent
                hasBackdrop>
                <View style={styles.modalContainer}>
                    <Text style={styles.modalTitle}>{t('DeviceDetailes.t20')}</Text>
                    <View style={[styles.input]}>
                        <TextInput
                            style={styles.inputStyle}
                            placeholder={t('DeviceDetailes.t21')}
                            returnKeyType={'done'}
                            value={deviceAlias}
                            maxLength={15}
                            onChangeText={(val) => {
                                setDeviceAlias(val);
                            }}
                            placeholderTextColor={'#a4a4a4'}
                        />
                    </View>
                    <TouchableOpacity style={[styles.bootom_button, styles.bt]} onPress={saveDeviceAlias}>
                        <Text style={styles.bootom_buttonText}>{t('DeviceDetailes.t22')}</Text>
                    </TouchableOpacity>
                </View>
            </Modal>
            <DialogModal
                key="unbind"
                visible={unbindVisible}
                content={t('DeviceDetailes.t23')}
                onCancel={() => setUnbindVisible(false)}
                onConfirm={unbindDevice}
            />
            <DialogModal
                key="recoverModal"
                visible={recoverVisible}
                content={t('DeviceDetailes.t24')}
                onCancel={() => setRecoverVisible(false)}
                onConfirm={recover}
            />
            <MyLoading ref={loadingRef} title={t('DeviceDetailes.t28')} />
        </View>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    container: { flex: 1 },
    bg: {
        flex: 1,
        resizeMode: 'contain',
        paddingHorizontal: px2dp(24),
        position: 'relative',
    },
    upload: {
        width: px2dp(50),
        height: px2dp(50),
        tintColor: '#fff',
    },
    title: {
        color: '#fff',
        fontSize: scale(30),
    },
    contenetStyle: {
        flexGrow: 1,
        paddingBottom: '30%',
    },
    barContainer: {
        width: px2dp(20),
        height: px2dp(300),
        backgroundColor: '#eee',
        borderRadius: px2dp(9999),
        overflow: 'hidden',
        justifyContent: 'flex-end',
        marginLeft: px2dp(32),
    },
    bar: {
        width: '100%',
        backgroundColor: '#1DCE87',
    },
    barBackground: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: '#eee',
    },
    eq: {
        color: '#fff',
        fontSize: scale(72),
    },
    device_code: {
        color: '#A4A4A4',
        fontSize: scale(32),
        marginTop: px2dp(12),
    },
    device_image: {
        width: px2dp(306),
        height: px2dp(500),
    },
    card: {
        borderWidth: 1,
        borderColor: 'rgba(255, 255, 255, 0.12)',
        borderRadius: px2dp(16),
        padding: px2dp(24),
        marginTop: px2dp(32),
    },
    setList: {
        borderBottomWidth: 1,
        borderColor: 'rgba(255, 255, 255, 0.12)',
        height: px2dp(120),
    },
    menue: {
        flexDirection: 'row',
        alignItems: 'center',
        flexWrap: 'wrap',
    },
    listItem: {
        alignItems: 'center',
        width: (width - px2dp(100)) / 4,
        marginTop: px2dp(24),
    },
    icons: {
        width: px2dp(70),
        height: px2dp(70),
    },
    t1: {
        color: '#A4A4A4',
        fontSize: scale(28),
        marginTop: px2dp(12),
    },
    card_title: {
        color: '#fff',
        fontSize: scale(28),
        fontWeight: 'bold',
        marginBottom: px2dp(24),
    },
    bottom: {
        paddingVertical: px2dp(60),
        position: 'absolute',
        bottom: 0,
        width: width,
    },
    bootom_button: {
        backgroundColor: '#242D56',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(999),
        height: px2dp(100),
        marginHorizontal: px2dp(32),
    },
    bootom_buttonText: {
        color: '#fff',
        fontSize: scale(32),
        fontWeight: 'bold',
    },
    nav: {
        marginTop: '10%',
    },
    tips: {
        color: '#FFFFFF',
        fontSize: scale(32),
        fontWeight: 'bold',
        letterSpacing: 1.2,
        marginRight: px2dp(12),
    },
    modalContainer: {
        padding: px2dp(24),
        backgroundColor: '#fff',
        borderColor: 'rgba(255, 255, 255, 0.12)',
        borderRadius: px2dp(22),
    },
    input: {
        borderWidth: 1,
        borderColor: '#eee',
        borderRadius: px2dp(16),
        paddingHorizontal: px2dp(16),
        height: px2dp(100),
        justifyContent: 'center',
        marginTop: px2dp(16),
    },
    inputStyle: {
        color: '#000',
        fontSize: scale(28),
    },
    modalTitle: {
        color: '#000',
        textAlign: 'center',
        fontSize: scale(30),
        marginBottom: px2dp(32),
    },
    bt: {
        backgroundColor: '#242D56',
        borderColor: '#242D56',
        marginTop: px2dp(32),
    },
    switchIcon: {
        width: px2dp(120),
        height: px2dp(50),
    },
});
